package com.xinghanlaser.applet.base.auth.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.xinghanlaser.applet.base.common.entity.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.xinghanlaser.applet.base.common.enums.ResponseCodeEnum.UN_AUTH_TOKEN;

/**
 * <p>
 * 处理用户认证未通过的场景
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/4/29 13:46
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(objectMapper.writeValueAsString(ResponseEntity.fault(UN_AUTH_TOKEN, "未携带Token或Token无效")));
    }
}
